package cn.chengpengper.unit18.server.handler;

import cn.chengpengper.unit18.protocol.request.JoinGroupRequestPacket;
import cn.chengpengper.unit18.protocol.response.JoinGroupResponsePacket;
import cn.chengpengper.unit18.util.SessionUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;

/**
 * @author huchengpeng
 */
public class JoinGroupRequestHandler extends SimpleChannelInboundHandler<JoinGroupRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, JoinGroupRequestPacket request) throws Exception {
        // 1、获取群对应的 ChannelGroup,然后将当前用户的 Channel 添加进去
        String groupId = request.getGroupId();
        ChannelGroup channelGroup = SessionUtil.getChannelGroup(groupId);
        channelGroup.add(ctx.channel());

        JoinGroupResponsePacket responsePacket = new JoinGroupResponsePacket();
        responsePacket.setSuccess(true);
        responsePacket.setGroupId(groupId);
        ctx.channel().writeAndFlush(responsePacket);
    }
}
